<template>
  <div class="order-management">
    <el-card>
      <!-- 操作栏 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="平台名称">
          <el-select v-model="searchForm.platformName" placeholder="全部">
            <el-option
              v-for="item in platformNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单编号">
          <el-input v-model="searchForm.id" placeholder="请输入订单编号"></el-input>
        </el-form-item>

        <el-form-item label="用户名称">
          <el-input v-model="searchForm.consumerName" placeholder="请输入用户名称"></el-input>
        </el-form-item>

        <el-form-item label="商品id">
          <el-input v-model="searchForm.goodName" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status">
            <el-option
              v-for="status in orderStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="订单创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDeleteBatch">批量删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="uploadExcelDialog=true">导入</el-button>
          <el-button type="primary"  @click="downloadExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <!-- 数据展示层 -->
    <el-table :data="tableData" border
              style="width: 100%"
              @selection-change="handleSelectionChange"
              @row-click="handleEdit">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="平台订单号" />
      <el-table-column prop="platformName" label="平台名称" />
      <el-table-column prop="consumerName" label="用户名称" />
      <el-table-column prop="goodName" label="商品名称" />
      <el-table-column prop="amount" label="订单金额(元)" />
      <el-table-column prop="logistics" label="物流方式" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="getOrderStatusTagType(scope.row.status)"
            size="small"
          >{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '待发货'"
            size="mini"
            type="primary"
            @click.stop="openShipDialog(scope.row)"
          >发货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--      新增/修改表单-->
    <el-dialog :title= this.title :visible.sync="dialogVisible" width="60%"
                >
      <el-form :model="Editform" :rules="rules"  ref="Editform" label-width="100px">

        <el-form-item label="平台" prop="platformName">
          <el-select v-model="Editform.platformName" placeholder="请选择供应商" style="width: 100%;">
            <el-option
              v-for="item in platformNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="consumerName">
          <el-input v-model="Editform.consumerName" placeholder="请输入用户名称"
                    :disabled="title === '修改'"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model.number="Editform.goodName" placeholder="请输入商品名称"
                    :disabled="title === '修改'"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单总金额">
          <el-input v-model.number="Editform.amount"
                    :disabled="title === '修改'"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单状态" v-if="this.title ==='修改'?true:false">
          <el-select
            v-model="Editform.status"
            placeholder="全部"
            clearable
          >
            <el-option
              v-for="status in orderStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="Editform.remark" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onClose">关 闭</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 发货弹窗 -->
    <el-dialog title="选择物流公司" :visible.sync="shipDialogVisible" width="30%">
      <el-form label-width="100px">
        <el-form-item label="物流公司">
          <el-select v-model="selectedLogistics" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰" value="顺丰"></el-option>
            <el-option label="中通" value="中通"></el-option>
            <el-option label="邮政" value="邮政"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="shipDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmShip">确 定</el-button>
  </span>
    </el-dialog>

    <!-- 文件上传弹窗 -->
    <el-dialog title="上传文件" :visible.sync="uploadExcelDialog" width="30%">
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelFun"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>

        <el-button type="primary" @click="">确 定</el-button>

      </div>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15]"
      :page-size="queryPage.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
    />



  </div>
</template>

<script>
import {
  addOrderplatform,
  deleteOrderplatform,
  findAllByPage, findAllPlatformName,
  updateOrderplatform,
  uploadExcel
} from '@/api/order/orderPlatform'
export default {
  name: 'orderPlatform',
  data() {
    return {
      uploadExcelDialog:false,
      file: null,
      fileList: [],
      platformNameOptions:[],
      shipDialogVisible: false, // 控制发货弹窗显示
      selectedLogistics: '',   // 当前选择的物流公司
      currentRow: null,         // 当前行数据
      // 添加验证规则
      rules: {
        platformName: [
          { required: true, message: '平台ID不能为空', trigger: 'blur' },
        ],
        consumerName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '订单金额不能为空', trigger: 'blur' },
        ]
      },
      orderStatusOptions: [
        { value: '待发货', label: '待发货' },
        { value: '已发货', label: '已发货' },
        { value: '交易成功', label: '交易成功' },
      ],
      //复选框
      multipleSelection:[],
      title:'',
      dialogVisible:false,
      Editform: {
        supplier: '',
        warehouse: '',
        quantity: '',
        unitPrice: '',
        taxAmount: '', // 税后金额
        orderStatus: '',
        deliveryDate: '',
        remark: ''
      },
      // 搜索栏
      searchForm:{
      },
      queryPage:{
        pageNum: 1,
        pageSize: 5
      },
      tableData: [],
      currentPage: 1,
      pageNum: 1,
      pageSize: 10,
      total: 0,
    }
  },
  created() {
    this.loadData();
  },

  methods: {
    getOrderStatusTagType(status){
      switch (status) {
        case '待发货':
          return 'warning'; // 黄色 tag
        case '已发货':
          return 'info'; // 灰色 tag
        case '交易成功':
          return 'success'; // 绿色 tag
        default:
          return '';
      }
    },
    downloadExcel(){
      this.$confirm(`确定要下载Excel吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href="http://localhost:8888/order/platform/download/excel"
        this.$message({
          message: '下载成功!',
          type: 'success',
          duration: 1200
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下载'
        });
      });
    },
    beforeUpload(){
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    uploadExcelFun() {
      const file = this.file;
      const formData = new FormData();
      formData.append('file', file);
      //封装文件上传的方法
      uploadExcel(formData).then(res => {
        if (res.code === 20000) {
          this.$message.success('上传成功');
          //上传成功后添加到文件列表
          this.fileList.push({
            name: file.name,
          });
          this.uploadExcelDialog = false;
          this.pageNum = 1;
          this.loadData()
        } else {
          this.$message.error(res.message || '上传失败');
        }
      })
    },
    handleChange(file) {
      this.file = file.raw;
    },
    confirmShip() {
      if (!this.selectedLogistics) {
        this.$message.warning('请选择物流公司');
        return;
      }

      // 构造更新后的订单对象
      const updatedOrder = {
        ...this.currentRow,
        status: '已发货',
        logistics: this.selectedLogistics // 可以提交到后端
      };

      // 调用修改接口
      updateOrderplatform(updatedOrder).then(res => {
        if (res.code === 20000) {
          this.$message.success('发货成功');
          this.shipDialogVisible = false;
          this.loadData(); // 刷新表格
        } else {
          this.$message.error(res.message || '发货失败');
        }
      }).catch(() => {
        this.$message.error('网络异常，请重试');
      });
    },
    // 打开发货弹窗的方法
    openShipDialog(row) {
      this.currentRow = { ...row }; // 复制当前行数据
      this.selectedLogistics = '';  // 清空上次选择
      this.shipDialogVisible = true;
    },
    // 关闭
    onClose(){
      this.dialogVisible = false
      this.Editform = {}
      this.handleReset()

    },
    // 批量删除
    handleDeleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('此操作将永久删除选中的文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        // distinguishCancelAndClose: true,    // 重要，设置为true才会把右上角X和取消区分开来
        // closeOnClickModal: false
      }).then(() => {// 用户点击确定进入此流程
        const ids = this.multipleSelection.join(',')
        deleteOrderplatform(ids)
          .then(ret => {
            if (ret.code === 20000) {
              this.$message.success('批量删除成功')
              this.queryPage.pageNum = 1
              this.loadData()
            }else{
              this.$message.error(ret.message || '删除失败')
            }
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    //select方法监控
    handleSelectionChange(val){
      this.multipleSelection = val.map(item => item.id)
    },
    // 新增/修改表单的提交
    onSubmit(){
      this.$refs.Editform.validate(valid => {
        if (!valid) {
          this.$message.error('请正确填写表单')
          return
        }
        if(this.title ===  '新增'){
          console.log('新增')
          addOrderplatform(this.Editform).then(res=>{
            if(res.code == 20000){
              this.$message.success('添加成功！');
              this.dialogVisible = false;
              this.loadData();
              this.Editform = {}
            }else{
              this.$message.error('添加失败！');
            }
          })
        }
        if(this.title === '修改'){
          console.log('修改')
          updateOrderplatform(this.Editform).then(res=>{
            if(res.code == 20000){
              this.$message.success('修改成功！');
              this.dialogVisible = false;
              this.loadData();
              this.Editform = {}
            }else{
              this.$message.error('修改失败！');
            }
          })
        }
      })
    },

    //分页-页码大小改变
    handleSizeChange(newSize) {
      this.queryPage.pageSize = newSize
      this.loadData()
    },
    //分页-当前页码数改变
    handleCurrentChange(page){
      this.queryPage.pageNum = page;
      this.loadData();
    },
    // 加载数据
    loadData(){
      findAllByPage(this.queryPage).then(res=>{
        if(res.code == 20000){
          console.log(res)
          this.tableData = res.data.list;
          this.total = res.data.total
        }else{
          this.$message.error(res.message);
        }
      })
      findAllPlatformName().then(res=>{
        if(res.code == 20000){
          console.log(res)
          this.platformNameOptions = res.data.map(item => ({
            label: item,
            value: item
          }));
          console.log(this.platformNameOptions)
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //查询
    handleSearch(){
      // 构建查询参数
      const params = { ...this.searchForm,
        createTime: undefined };

      // 重置分页
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;

      // 处理时间范围
      if (this.searchForm.createTime?.length === 2) {
        params.startDate = this.searchForm.createTime[0];
        params.endDate = this.searchForm.createTime[1];
      }
      // 合并查询参数和分页参数
      this.queryPage = { ...this.queryPage, ...params};

      // 加载数据
      this.loadData();
    },
    //重置
    handleReset(){
      this.searchForm = {};
      this.queryPage = {};
      this.queryPage.pageNum = 1;
      this.queryPage.pageSize = 5;
      this.Editform = {}
      this.loadData();
      this.$refs.Editform.resetFields();
    },
    handleAdd(){
      this.title = '新增'
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.title = '修改';
      this.dialogVisible = true;
      this.Editform = row ;
    },
    // 计算税金
    calculateTaxAmount() {
      const { quantity, unitPrice } = this.Editform;
      if (!quantity || !unitPrice) {
        this.Editform.taxAmount = '';
        return;
      }
      let subtotal = parseFloat(quantity) * parseFloat(unitPrice);
      if (subtotal < 2000) {
        this.Editform.taxAmount = subtotal.toFixed(2);
      } else {
        const taxableAmount = subtotal - 2000;
        const tax = taxableAmount * 0.015;
        this.Editform.taxAmount = (subtotal + tax).toFixed(2);
      }
    },
  },
  watch: {
    'Editform.quantity': function(newVal) {
      this.calculateTaxAmount();
    },
    'Editform.unitPrice': function(newVal) {
      this.calculateTaxAmount();
    }
  },
}
</script>


<style scoped lang="scss">
.order-management {
  padding: 20px；
}
.status-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;

  &.success {
    background-color: #a5d58d; // 绿色
  }

  &.default {
    background-color: #999; // 灰色
  }
}
</style>
